package com.example.dj;

import java.util.List;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service{
	private MediaPlayer mediaPlayer; // 媒体播放器对象
    private String path;            // 音乐文件路径  
    private int msg;  
    private boolean isPause;        // 暂停 
    private int current = 0;        // 记录当前正在播放的音乐
    private List<Mp3Info> mp3Infos;   //存放Mp3Info对象的集合
    private int status = 3;         //播放，默认为顺序播放  
    private MyReceiver myReceiver;  //自定义广播接收器  
    private int currentTime;        //当前播放进度  
    private int duration;
    
    public static final String UPDATE_ACTION = "com.example.action.UPDATE_ACTION";  // 更新动作
    public static final String CTL_ACTION = "com.example.action.CTL_ACTION";  // 控制动作
    public static final String MUSIC_CURRENT = "com.example.action.MUSIC_CURRENT";  // 当前音乐改变动作
    public static final String MUSIC_DURATION = "com.example.action.MUSIC_DURATION";  // 音乐时长改变动作
    
    
    private Handler handler= new Handler() {
    	public void handleMessage(android.os.Message msg) {  
            if (msg.what == 1) {  
                if(mediaPlayer != null) {  
                    currentTime = mediaPlayer.getCurrentPosition(); // 获取当前音乐播放的位置
                    Intent intent = new Intent();  
                    intent.setAction(MUSIC_CURRENT);  
                    intent.putExtra("currentTime", currentTime);  
                    sendBroadcast(intent); // 给PlayerActivity发广播  
                    handler.sendEmptyMessageDelayed(1, 1000);  
                }  
                  
            }  
        };  
    };
    
    @Override
    public void onCreate() {  
        super.onCreate();  
        Log.d("service", "service created");  
        mediaPlayer = new MediaPlayer();  
        mp3Infos = MediaUtil.getMp3Infos(MyService.this);
        
        //设置音乐播放完成时的监听器
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {  
        	@Override  
        	public void onCompletion(MediaPlayer mp) {  
        		if (status == 1) { // 全部循环  
                current++;
                if(current > mp3Infos.size() - 1) {  //变为第一首的位置继续播放  
                	current = 0;  
                }
                Intent sendIntent = new Intent(UPDATE_ACTION);  
                sendIntent.putExtra("current", current);  
                //发送广播，将被Activity组件中的BroadcastReceiver接收
                sendBroadcast(sendIntent);  
                path = mp3Infos.get(current).getUrl();  
                play(0);
                } else if (status == 2) { // 顺序播放  
        			current++;  //下一首位置 
        			if (current <= mp3Infos.size() - 1) {  
        				Intent sendIntent = new Intent(UPDATE_ACTION);  
                        sendIntent.putExtra("current", current);  
                        // 发送广播，将被Activity组件中的BroadcastReceiver接收
                        sendBroadcast(sendIntent);  
                        path = mp3Infos.get(current).getUrl();  
                        play(0);  
        			}else {  
        				mediaPlayer.seekTo(0);  
        				current = 0;  
        				Intent sendIntent = new Intent(UPDATE_ACTION);  
        				sendIntent.putExtra("current", current);  
        				// 发送广播，将被Activity组件中的BroadcastReceiver接收
        				sendBroadcast(sendIntent);  
        			}  
        		} else if(status == 3) {    //随机播放  
        			current = getRandomIndex(mp3Infos.size() - 1);  
        			System.out.println("currentIndex ->" + current);  
        			Intent sendIntent = new Intent(UPDATE_ACTION);  
        			sendIntent.putExtra("current", current);  
        			// 发送广播，将被Activity组件中的BroadcastReceiver接收
        			sendBroadcast(sendIntent);  
        			path = mp3Infos.get(current).getUrl();  
        			play(0);  
        		}  
        	}
        });  
      
            myReceiver = new MyReceiver();  
            IntentFilter filter = new IntentFilter();  
            filter.addAction(PlayActivity.CTL_ACTION);  
            registerReceiver(myReceiver, filter);  
        }
    
    //获取随机位置
	private int getRandomIndex(int end) {
		// TODO Auto-generated method stub
		int index = (int) (Math.random() * end);  
        return index;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override  
	public void onStart(Intent intent, int startId) { 
		path = intent.getStringExtra("url");        //歌曲路径  
		current = intent.getIntExtra("listPosition", -1);   //当前播放歌曲的在mp3Infos的位置
		msg = intent.getIntExtra("MSG", 0);         //播放信息  
		if (msg == AppConstant.PlayerMsg.PLAY_MSG) {    //直接播放音乐  
			play(0);  
			} else if (msg == AppConstant.PlayerMsg.PAUSE_MSG) {    //暂停  
				pause();      
			} else if (msg == AppConstant.PlayerMsg.STOP_MSG) {     //停止  
	            stop();  
	        } else if (msg == AppConstant.PlayerMsg.CONTINUE_MSG) { //继续播放  
	            resume();     
	        } else if (msg == AppConstant.PlayerMsg.PRIVIOUS_MSG) { //上一首
	            previous();  
	        } else if (msg == AppConstant.PlayerMsg.NEXT_MSG) {     //下一首 
	            next();  
	        } else if (msg == AppConstant.PlayerMsg.PROGRESS_CHANGE) {  //进度更新  
	            currentTime = intent.getIntExtra("progress", -1);  
	            play(currentTime);  
	        } else if (msg == AppConstant.PlayerMsg.PLAYING_MSG) {  
	            handler.sendEmptyMessage(1);  
	        }  
		super.onStart(intent, startId);
	}
	
	private void play(int currentTime) {
 		// TODO Auto-generated method stub
		try {  
            mediaPlayer.reset();// 把各项参数恢复到初始状态
            mediaPlayer.setDataSource(path);  
            mediaPlayer.prepare(); // 进行缓冲  
            mediaPlayer.setOnPreparedListener(new PreparedListener(currentTime));// 注册监听 
            handler.sendEmptyMessage(1);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
 	}
	
	private void next() {
		// TODO Auto-generated method stub
		Intent sendIntent = new Intent(UPDATE_ACTION);  
        sendIntent.putExtra("current", current);  
        // 发送广播，将被Activity组件中的BroadcastReceiver接收
        sendBroadcast(sendIntent);  
        play(0);
	}

	private void previous() {
		// TODO Auto-generated method stub
		Intent sendIntent = new Intent(UPDATE_ACTION);  
        sendIntent.putExtra("current", current);  
        sendBroadcast(sendIntent);  
        play(0);  
	}

	private void stop() {
		// TODO Auto-generated method stub
		if (mediaPlayer != null) {  
            mediaPlayer.stop();  
            try {  
                mediaPlayer.prepare(); 
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
	}

	private void pause() {
		// TODO Auto-generated method stub
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {  
            mediaPlayer.pause();  
            isPause = true;  
        } 
	}
	
	private void resume() {
		// TODO Auto-generated method stub
		if (isPause) {  
            mediaPlayer.start();  
            isPause = false;  
        }  
	}


	
	@Override  
    public void onDestroy() {  
        if (mediaPlayer != null) {  
            mediaPlayer.stop();  
            mediaPlayer.release();  
            mediaPlayer = null;  
        }  
    }  
	
	private final class PreparedListener implements OnPreparedListener{
		private int currentTime;  
		  
        public PreparedListener(int currentTime) {  
        	this.currentTime = currentTime;
        }
		@Override
		public void onPrepared(MediaPlayer mp) {
			// TODO Auto-generated method stub
			mediaPlayer.start(); // 播放  
            if (currentTime > 0) { // 如果音乐不是从头播放  
                mediaPlayer.seekTo(currentTime);  
            }  
            Intent intent = new Intent();  
            intent.setAction(MUSIC_DURATION);  
            duration = mediaPlayer.getDuration();  
            intent.putExtra("duration", duration);  //通过Intent来传递歌曲的总长
            sendBroadcast(intent);  
        }  
	}
	
	public class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			int control = intent.getIntExtra("control", -1);  
            switch (control) {  
            case 1:  
                status = 1; //全部播放
                break;  
            case 2:  
                status = 2; //顺序播放
                break;  
            case 3:  
                status = 3; //随机播放
                break;  
            }  
		}
		
	}
}
